<?php


namespace App\Logic\Order\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Logic\Group\GroupProfitService;
use App\Logic\Member\MemberProfitScoreService;
use App\Logic\Member\MemberService;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Order\OrderModel;
use EasySwoole\ORM\DbManager;
use App\Util\CommonHelper;

/**
 * CREATE TABLE `ss_order` (
 * `id` char(24) NOT NULL COMMENT '订单id',
 * `user_id` int(11) NOT NULL COMMENT '用户id',
 * `order_amount` decimal(10,2) NOT NULL COMMENT '订单实付金额',
 * `total_profit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '订单总收益',
 * `user_profit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '当前用户收益',
 * `referrer_profit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '团队收益',
 * `profit_chain` json DEFAULT NULL COMMENT '推荐链分级收益',
 * `order_state` char(10) NOT NULL DEFAULT 'UNSHIPPING' COMMENT '订单状态 CREATED:结算中;CANCELLED:已取消;SETTLED:已结算',
 * `order_date` date DEFAULT NULL COMMENT '订单日期',
 * `order_time` datetime DEFAULT NULL COMMENT '下单时间',
 * `cancel_time` datetime NOT NULL COMMENT '取消时间',
 * `settle_time` datetime DEFAULT NULL COMMENT '结算时间',
 * `created_at` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '创建时间',
 * `created_by` varchar(32) NOT NULL DEFAULT '' COMMENT '创建人员账号',
 * `updated_at` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
 * `updated_by` varchar(32) NOT NULL DEFAULT '' COMMENT '最后更新人员账号',
 * `is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除[0:未删除，1：已删除]',
 * `deleted_at` datetime NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT '删除时间',
 * PRIMARY KEY (`id`) USING BTREE,
 * UNIQUE KEY `user_id` (`user_id`,`order_date`,`deleted_at`) USING BTREE,
 * KEY `created_at` (`created_at`) USING BTREE,
 * KEY `order_date` (`order_date`) USING BTREE
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='结算订单';
 */
class SubmitOrderForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $date;
    public $today;
    public $_memberModel;
    public $_productModel;
    public $_accountModel;

    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'user_id' => ['required|integer'],
            'date' => ['required'],
        ];
    }

    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();

        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
//        $this->user_id = UserIdentityHelper::getId();
        //校验会员信息
        if (empty($this->getMember())) {
            throw new DefaultException('会员不存在');
        }

        /**指定日期是否有订单,有的话提示错误*/
        $date = strtotime($this->date);
        if ($date > time()){
            throw new DefaultException('日期不能大于当前日期');
        }
        $this->today        = date('Y-m-d', $date);
        $res = OrderModel::getOne(['user_id' => $this->user_id, 'order_date' => $this->today]);
        if (!empty($res)){
            throw new DefaultException('当日已有结算单,请勿重复提交~');
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            /**收益*/
            list($totalProfit, $userProfit, $referrerProfit, $profitChain) = self::genProfit();

            $now     = date('Y-m-d H:i:s');
            //添加订单主表
            $orderData = [
                'user_id'         => $this->user_id,
                'order_amount'    => $this->getMember()->score,
                'order_state'     => OrderModel::SETTLED,
                'order_date'      => $this->today,
                'order_time'      => $now,//下单时间
                'settle_time'     => $now, //结算时间
                'total_profit'    => $totalProfit,
                'user_profit'     => $userProfit,
                'referrer_profit' => $referrerProfit,
                'profit_chain'    => json_encode($profitChain),
                'created_at'      => $now,//创建
                'created_by'      => 'system',
            ];

            $result = OrderModel::insertData($orderData);
            $orderId = $result->lastQueryResult()->getLastInsertId();
            /**用户收益*/
            $userProfitScore = bcmul($orderData['order_amount'], $userProfit/100, 2);
            if($userProfitScore <= 0){
                throw new DefaultException('用户收益为0');
            }
            MemberProfitScoreService::getInstance()->change($this->user_id, $userProfitScore, MemberProfitScoreModel::TYPE_USER_PROFIT, $orderId, $this->user_id, '个人收益');

            /**推荐收益*/
            foreach ($profitChain as $k => $item){
                /**如果用户id不为空
                 * 并且profit>=0
                 * 那么给用户发放团队收益
                 * 更新用户团队收益统计
                 * */
                $item['profit'] = $item['profit'] - 0;
                if(!empty($item['id']) && $item['profit'] > 0){
                    $source_id = $k == 0 ? $this->user_id : $profitChain[$k-1]['id'];
                    $profitScore = bcmul($orderData['order_amount'], $item['profit']/100);
                    MemberProfitScoreService::getInstance()->change($item['id'], $profitScore, MemberProfitScoreModel::TYPE_REFFERER_PROFIT, $orderId, $source_id, '团队收益');
                    GroupProfitService::getInstance()->profit($item['id'], $source_id, $profitScore);
                }
            }
            /**更新用户最后收益时间*/
            MemberModel::updateData(['last_profit_time' => $now], ['id' => $this->user_id]);

            DbManager::getInstance()->commitWithCount('write');
            $result     = $this->success( ['id' => $orderId]);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }

    public function getMember()
    {
        if ($this->_memberModel === null) {
            $user_id            = $this->user_id;
            $this->_memberModel = MemberModel::getOne(['id' => $user_id]);
        }
        return $this->_memberModel;
    }

    /**
     * 生成收益
     */
    public function genProfit()
    {
        $profitChain = MemberService::getInstance()->findAllRecommendedChainProfit($this->getMember()->id);
        $firstProfit = reset($profitChain);
        $lastProfit  = end($profitChain);
        if (empty($firstProfit) || empty($lastProfit)) {
            throw new \Exception('收益比例错误!');
        }
        /**总收益比例*/
        $totalProfit = $lastProfit['profit'];
        /**用户收益比例*/
        $userProfit = $firstProfit['profit'];
        /**团队收益比例*/
        $referrerProfit = bcsub($totalProfit, $userProfit, 2);
        /**级差收益比例链*/
        $profits = [];
        for ($i = 1; $i < count($profitChain); $i++) {
            $profits[] = [
                'id'     => $profitChain[$i]['id'],
                'profit' => bcsub($profitChain[$i]['profit'], $profitChain[$i - 1]['profit'], 2),
                'origin' => $profitChain[$i]['profit'],
            ];
        }
        return [$totalProfit, $userProfit, $referrerProfit, $profits];
    }

}
